$(function () {
  queryUserList()
  renderDict()
})


/* 组件示例-选择机构 */
var deptRows = []

function selectDept() {
  var url = "/pages/tool/example/deptTree";
  var options = {
    title: '选择部门',
    width: "480",
    url: url,
    callBack: doSubmit
  };
  var deptIds = []
  deptRows.forEach(function (dept) {
    deptIds.push(dept.deptId)
  })
  $.modal.openOptionsInitData(options, deptIds);
}

function doSubmit(index, layero) {
  var rows = layero.find('iframe')[0].contentWindow.$._tree.getCheckedNodes()
  deptRows = []
  var deptText = ''
  rows.forEach(function (row) {
    deptRows.push({
      deptName: row.name,
      deptId: row.id
    })
    deptText += row.name + '，'
  })
  $('#treeName').val(deptText.slice(0, deptText.length - 1))
  layer.close(index);

  /* 获取客户列表 */
  selectUser()
  $('#autoSelect').attr("disabled", !Boolean(deptRows.length)) //选了机构之后才能选择用户

  selectUserMu()
  $('#autoSelectMu').attr("disabled", !Boolean(deptRows.length)) //选了机构之后才能选择用户
}

/* 组件示例-选择用户单选 */
function selectUser() {
  var list = []
  /* 获取所有用户用于搜索 */
  $.ajax({
    url: '/admin/user/page',
    //        data: {"param": request.term},
    data: {size: 10, current: 1},
    type: 'GET',
    success: function (data) {
      list = data.data.records.map(function (item) {
        return {
          label: item.loginname + '-' + item.username,
          value: item.loginname + '-' + item.username,
          userId: item.userId
        }
      });


      /* 初始化搜索input框  */
      $("#autoSelect").autocomplete({
        //minLength: 2,
        autoFocus: true,
        select: function (event, ui) {
        },
        //                source: list,
        source: function (request, response) {
          var term = request.term;
          var result = $.ui.autocomplete.filter(list, term)
          if (result.length > 0) {
            response(result);
          } else {
            response(['null']);
            $(".ui-autocomplete").html('<div style="margin:10px auto;text-align: center;color: #999;"><i class="fa fa-exclamation"></i> 无匹配结果</div>');
          }
        },
        focus: function () {
          // 防止在获得焦点时插入值
          return false;
        },
      }).click(function () {
        $(this).autocomplete("search");
      });


    },

  });


}

/* 组件示例-选择用户多选 */
function selectUserMu() {
  var list = []
  /* 获取所有用户用于搜索 */
  $.ajax({
    url: '/admin/user/page',
    //        data: {"param": request.term},
    data: {size: 10, current: 1},
    type: 'GET',
    success: function (data) {
      list = data.data.records.map(function (item) {
        return {
          label: item.loginname + '-' + item.username,
          value: item.loginname + '-' + item.username,
          userId: item.userId
        }
      });


      /* 初始化搜索input框  */
      $("#autoSelectMu").on("keydown", function (event) {
        if (event.keyCode === $.ui.keyCode.TAB &&
          $(this).data("ui-autocomplete").menu.active) {
          event.preventDefault();
        }
      }).autocomplete({
        //minLength: 2,
        autoFocus: true,
        select: function (event, ui) {
          //                    console.log('选中的选项',ui);
          //                    console.log($(event.target).val()); //获取输入框对象

          var terms = split(this.value);
          // 移除当前所有的内容
          terms.pop();
          if (terms.indexOf(ui.item.value) == -1) { //判断是否已选中过当前点击的选项
            // 将选中的添加到input中
            terms.push(ui.item.value);
            // 在最后添加分隔符
            terms.push("");
            this.value = terms.join(", ");
          }

          return false;

        },
        //                source: list,
        source: function (request, response) {
          var term = request.term;
          var result = $.ui.autocomplete.filter(list, extractLast(term))
          if (result.length > 0) {
            response(result);
          } else {
            response(['null']);
            $(".ui-autocomplete").html('<div style="margin:10px auto;text-align: center;color: #999;"><i class="fa fa-exclamation"></i> 无匹配结果</div>');
          }


        },
        focus: function () {
          // 防止在获得焦点时插入值
          return false;
        },
      }).click(function () {
        $(this).autocomplete("search");
      });

    },

  });


}

function split(val) {
  return val.split(/,\s*/);
}

function extractLast(term) {
  return split(term).pop();
}


/** 列表导入导出 **/
function tableInit() {

}

function queryUserList() {
  var options = {
    url: api + "/admin/user/page",
    updateUrl: "/pages/sysadm/user/userEdit",
    removeUrl: api + "/admin/user/{id}",
    exportUrl: api + "/admin/user/doExport",
    importUrl: api + "/admin/user/importData",
    importTemplateUrl: api + "/importTemplate",
    sortName: "createTime",
    sortOrder: "desc",
    modalName: "用户",
    queryParams: function (params) { //因为后端只有用户管理这个接口descs传参为u.create_time，所以只对这个列表重新定义queryParams
      var data = {
        size: params.limit,
        current: (params.offset / params.limit + 1),
        search: params.search,
        descs: 'u.create_time',
      };
      if ($('input[name=loginname]').val()) data.loginname = $('input[name=loginname]').val()
      if ($('input[name=username]').val()) data.username = $('input[name=username]').val()
      return data
    },
    columns: [
      {
        checkbox: true
      },
      {
        field: 'userId',
        title: '用户Id',
        visible: false
      },
      {
        field: 'loginname',
        title: '登录名称'
      },
      {
        field: 'username',
        title: '用户名称'
      },
      {
        field: 'deptName',
        title: '所属部门'
      },
      {
        field: 'phone',
        title: '手机'
      },
      {
        // visible : editFlag == 'hidden' ? false : true,
        title: '用户状态',
        align: 'center',
        formatter: function (value, row, index) {
          return value == 9 ? '锁定' : '有效';
        }
      },
      {
        field: 'createTime',
        title: '创建时间'
      },
      {
        title: '操作',
        align: 'center',
        formatter: function (value, row, index) {
          var actions = [];
          return actions.join('');
        }
      }]
  };
  $.table.init(options);
}

function downloadFile() {
  /*var url = api + '/admin/statistic/doExport'
  var data = {server: 'sca-upms-biz'}
  $.table.downloadFile(url, data, '组件统计汇总')*/
  var suffix="?Authorization="+'Bearer ' + session.get('token')+"&TENANT-ID="+session.get('tenantId');
  $.modal.confirm("确定要导出吗？", function() {
    location.href =  api + '/admin/user/doExport'+suffix;
    layer.msg('执行成功,正在后台统计请稍后…', {
      icon: 1
    });
  })

}

function renderDict(){
  var dict = dictByType('param_type')
  renderTpl('selectDictTpl', {list: dict}, 'systemFlag')
}




